package com.lm.httpclient.controller;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import lombok.var;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Objects;

public class KgwebController {
    /**
     * 总数
     */
    private static final int AT_PAGE_END_NO = 1;

    /**
     * 起始
     */
    private static final int AT_PAGE_START_NO = 1;

    /**
     * 古籍的图片
     */
    private static  final  String AT_HOST = "http://kgnewapi.renrentong.cn";

    /**
     * 获取目录结构
     */
    private static final  String AT_BOOK_STRUCT ="/api/AtBook/GetBookStruct?en=js&book_id=";

    /**
     * 本地存储路径
     */
    private static final String SAVE_BASE_PATH = "d:\\webat";

   private static void pullATWebImages(){
       // 创建HttpClient实例
       try (CloseableHttpClient httpClient = HttpClients.createDefault()) {

           StringBuilder sb = new StringBuilder();
           sb.append(AT_HOST);
           sb.append("/api/AtBook/GetList?en=js&pageIndex=");
           sb.append(AT_PAGE_START_NO);
           sb.append("&pageSize=");
           sb.append(AT_PAGE_END_NO);
           sb.append("&orderType=py&parame=%7B%22areaname%22%3A%22%22%2C%22areaCode%22%3A%22%22%2C%22cat_id%22%3A%22%22%2C%22pub_s_date%22%3A%22%22%2C%22pub_e_date%22%3A%22%22%2C%22lb_label_name%22%3A%22%22%2C%22title_py%22%3A%22%22%2C%22pubdate_year%22%3A%22%22%2C%22contributor%22%3A%22%22%7D");

           URL url = new URL(sb.toString());
           // 创建GET请求
           HttpGet request = new HttpGet(url.toURI());

           // 执行请求并获取响应
           try (CloseableHttpResponse response = httpClient.execute(request)) {

               // 获取响应体
               HttpEntity entity = response.getEntity();

               if (Objects.nonNull(entity)) {
                   // 将响应体转为字符串
                   String result = EntityUtils.toString(entity);
                   if(Objects.nonNull(result)){
                       JSONObject obj = JSON.parseObject(result);
                       JSONArray data = obj.getJSONArray("data");
                       if(Objects.nonNull(data) && data.size() > 0){
                           analysisWebImages(data);
                       }
                   }
               }
           }
       }  catch (Exception e) {
           throw new RuntimeException(e);
       }
   }

   private static  void analysisWebImages(JSONArray jsonArray) throws Exception{
       jsonArray.forEach(obj->{
           JSONObject jsonObject = (JSONObject)obj;
           String bookId = jsonObject.getString("book_id");
           String bookName = jsonObject.getString("book_name");
           String mainPath = jsonObject.getString("mainPath");
           Path baseDir = Paths.get(SAVE_BASE_PATH);

           if(!Files.exists(baseDir)){
               try {
                   Files.createDirectories(baseDir);
               } catch (IOException e) {
                   throw new RuntimeException(e);
               }
           }

           Path bookDir = Paths.get(SAVE_BASE_PATH, bookName);
           try {
               Files.createDirectories(bookDir);
           } catch (IOException e) {
               throw new RuntimeException(e);
           }

           GetBookStruct(bookId, mainPath, bookDir.toString());
       });
   }

   private static void  GetBookStruct(String bookId, String mainPath, String savePath){
       // 创建HttpClient实例
       try (CloseableHttpClient httpClient = HttpClients.createDefault()) {

           String url = AT_HOST + AT_BOOK_STRUCT + bookId;
           // 创建GET请求
           HttpGet request = new HttpGet(url);

           // 执行请求并获取响应
           try (CloseableHttpResponse response = httpClient.execute(request)) {

               // 获取响应体
               HttpEntity entity = response.getEntity();

               if (Objects.nonNull(entity)) {
                   // 将响应体转为字符串
                   String result = EntityUtils.toString(entity);
                   if(Objects.nonNull(result)){
                       JSONObject obj = JSON.parseObject(result);
                       if(Objects.nonNull(obj)){
                           JSONArray data = obj.getJSONArray("data");
                           JSONArray dataOtherPage = obj.getJSONArray("data_OtherPage");
                           JSONArray dataEmptyPage = obj.getJSONArray("data_EmptyPage");
                           if(Objects.nonNull(data)){
                               data.forEach(d->{
                                   JSONObject jsonObject = (JSONObject)d;
                                   //String bookId =jsonObject.getString("book_id");
                                   Integer foreCoverNum =jsonObject.getInteger("fore_cover_num");
                                   Integer preface1Num = jsonObject.getInteger("preface1_num");
                                   Integer contentNum = jsonObject.getInteger("content_num");
                                   Integer preface2Num = jsonObject.getInteger("preface2_num");
                                   Integer textNum = jsonObject.getInteger("text_num");
                                   Integer appendixNum = jsonObject.getInteger("appendix_num");
                                   Integer backCoverNum = jsonObject.getInteger("back_cover_num");
                                   Integer textStartPage = jsonObject.getInteger("text_start_page");

                                   Integer textBeforNum = foreCoverNum + preface1Num + contentNum + preface2Num;

                                   var j = 1;
                                   for (var i = 1; i <= foreCoverNum; i++) {
                                       //a 页前锋
                                       String num = "00000" + i;
                                       num = num.substring(num.length() - 5);
                                       String picUrl = mainPath + bookId + "/a" + num + "_00.jpg";
                                       String localPicPath = savePath + "/a" + num + "_00.jpg";
                                       downloadImage(picUrl, localPicPath);
                                   }

                                   for (var i = 1; i <= preface1Num; i++) {
                                       //b 目录页之前的前附页
                                       String num = "00000" + i;
                                       num = num.substring(num.length() - 5);
                                       String picUrl = mainPath + bookId + "/b" + num + "_00.jpg";
                                       String localPicPath = savePath + "/b" + num + "_00.jpg";
                                       downloadImage(picUrl, localPicPath);
                                   }

                                   for (var i = 1; i <= contentNum; i++) {
                                       //c 目录页
                                       String num = "00000" + i;
                                       num = num.substring(num.length() - 5);
                                       String picUrl = mainPath + bookId + "/c" + num + "_00.jpg";
                                       String localPicPath = savePath + "/c" + num + "_00.jpg";
                                       downloadImage(picUrl, localPicPath);
                                   }

                                   for (var i = 1; i <= preface2Num; i++) {
                                       //d 目录页之后的后附页
                                       String num = "00000" + i;
                                       num = num.substring(num.length() - 5);
                                       String picUrl = mainPath + bookId + "/d" + num + "_00.jpg";
                                       String localPicPath = savePath +  "/d" + num + "_00.jpg";
                                       downloadImage(picUrl, localPicPath);
                                   }
                                   textBeforNum = j;
                                   for (var i = textStartPage; i < textNum + textStartPage; i++) {
                                       //t 正文页
                                       String num = "00000" + i;
                                       num = num.substring(num.length() - 5);
                                       String picUrl = mainPath + bookId + "/t" + num + "_00.jpg";
                                       String localPicPath = savePath +  "/t" + num + "_00.jpg";
                                       downloadImage(picUrl, localPicPath);
                                   }

                                   for (var i = 1; i <= appendixNum; i++) {
                                       //y 后附页
                                       String num = "00000" + i;
                                       num = num.substring(num.length() - 5);
                                       String picUrl = mainPath + bookId + "/y" + num + "_00.jpg";
                                       String localPicPath = savePath +  "/y" + num + "_00.jpg";
                                       downloadImage(picUrl, localPicPath);
                                   }

                                   for (var i = 1; i <= backCoverNum; i++) {
                                       //z 后封页
                                       String num = "00000" + i;
                                       num = num.substring(num.length() - 5);
                                       String picUrl = mainPath + bookId + "/z" + num + "_00.jpg";
                                       String localPicPath = savePath +  "/z" + num + "_00.jpg";
                                       downloadImage(picUrl, localPicPath);
                                   }
                               });
                           }
                       }
                   }
               }
           }
       }  catch (IOException e) {
           throw new RuntimeException(e);
       }
   }

    public static void downloadImage(String url, String destinationPath) {
        // 创建一个CloseableHttpClient实例
        try (CloseableHttpClient httpClient = HttpClients.createDefault()) {
            // 创建一个HttpGet请求
            HttpGet httpGet = new HttpGet(url);

            // 执行请求并获取响应
            try (CloseableHttpResponse response = httpClient.execute(httpGet)) {
                // 检查响应状态码
                int statusCode = response.getStatusLine().getStatusCode();
                if (statusCode == 200) {
                    // 获取响应的实体内容
                    HttpEntity entity = response.getEntity();
                    if (entity != null) {
                        // 创建输入流读取内容
                        try (InputStream inputStream = entity.getContent();
                             FileOutputStream outputStream = new FileOutputStream(new File(destinationPath))) {
                            byte[] buffer = new byte[4096];
                            int bytesRead;
                            // 读取并写入文件
                            while ((bytesRead = inputStream.read(buffer)) != -1) {
                                outputStream.write(buffer, 0, bytesRead);
                            }
                            System.out.println("Image downloaded successfully to " + destinationPath);
                        }
                    }
                    // 确保实体完全消耗掉
                    EntityUtils.consume(entity);
                } else {
                    System.out.println("Failed to download image. HTTP status code: " + statusCode);
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) {
        pullATWebImages();
    }
}
